<?php
/**
 * 异步mysql
 * @Author   Wcj
 * @DateTime 2019/3/14 16:00
 */

class AsyncMysql
{
    // 数据库连接参数常量值
    const HOST = '127.0.0.1';
    const PORT = 3306;
    const USER = 'root';
    const PASSWORD = 'root';
    const DATABASE = 'girls';
    const CHARSET = 'utf8mb4';
    const TIMEOUT = 2;

    // 数据库连接实例
    private $dbConnection = null;

    // 数据库连接配置参数
    private $server = [
        'host' => self::HOST,
        'port' => self::PORT,
        'user' => self::USER,
        'password' => self::PASSWORD,
        'database' => self::DATABASE,
        'charset' => self::CHARSET, // 指定字符集
        'timeout' => self::TIMEOUT,  // 可选：连接超时时间（非查询超时时间），默认为SW_MYSQL_CONNECT_TIMEOUT（1.0）
    ];

    /**
     * AsyncMysql constructor.
     */
    public function __construct()
    {
        $this->dbConnection = new swoole_mysql();
    }

    /**
     * 连接数据库并执行
     * @Author   Wcj
     * @DateTime 2019/3/14 17:16
     * @return bool
     */
    public function exec()
    {
        $this->dbConnection->connect($this->server, function ($db, $r) {
            if ($r === false) {
                var_dump($db->connect_errno, $db->connect_error);
                die;
            }
            $db->begin(function ($db, $ret) {
                $db->query('select * from beauty', function (swoole_mysql $db, $r) {
                    if ($r === false) {
                        var_dump($db->error, $db->errno);
                    } elseif ($r === true) {
                        $db->commit(function($db, $result) {
                            echo "commit ok\n";
                        });
                    } else {
                        print_r($r);
                    }
                    $db->close();
                });
            });

        });

        return true;
    }
}

$sql = new AsyncMysql();
var_export($sql->exec());
